package com.zb.validation.demo.controller;

import com.zb.validation.demo.model.User;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public Object index(@Valid User user, BindingResult bindingResult) {
        List<ObjectError> error = null;
        //返回boolean 是为了验证@Validated后面bean 里是否有不符合注解条件的错误信息
        if (bindingResult.hasErrors()) {
            //获得所有错误信息返回list集合
            error = bindingResult.getAllErrors();
            for (ObjectError o : error) {
                System.err.println(o.getDefaultMessage());
                //获得不符合要求的message
                return o.getDefaultMessage();
            }

        }
        return null;
    }

}